import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import user from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用来存储用户登录后得到的token
    token: '',
    // 用来存储用户信息
    userInfo: {}
  },
  getters: {
    username: state => state.userInfo.username,
    user_pic: state => state.userInfo.user_pic,
    nickname: state => state.userInfo.nickname
  },
  mutations: {
    // 更新token
    UpdateToken (state, newToken) {
      state.token = newToken
    },
    // 更新用户信息
    UpdateUserInfo (state, info) {
      state.userInfo = info
    }
  },
  actions: {
    async initUserInfo (context) {
      const { data: res } = await user.getUserInfo()
      if (res.code === 0) {
        context.commit('UpdateUserInfo', res.data)
      }
    }
  },
  modules: {
  },
  plugins: [createPersistedState()]
})

// vuex的数据是存储在内存中，刷新则重置vuex的值
// 使用vuex-persistedstate 插件 npm i vuex-persistedstate@3.2.1 持久化存储
